package edu.xhu;

import java.util.ArrayList;
import java.util.Iterator;

import com.bean.CoursePoint;
import com.bean.StuCourseBean;
import com.constant.Constant;
import com.data.ScheduleData;
import com.net.ClientError;
import com.net.LoadData;
import com.net.RequestListener;
import com.net.RequestParameter;

import edu.xhu.EduSystemTimeTable.ModifyCourseListener;
import edu.xhu.util.DatabaseAdapter;
import edu.xhu.view.LoadingDialog;

import android.os.Build;
import android.os.Bundle;
import android.provider.AlarmClock;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class ShortCourseActivity extends Activity {

	private Button mBtnBack;					//返回按钮
	private Button mRexh;					//刷新按钮
	private Resources mResources;
	
	private XhuApplication application;
	
	private LinearLayout mScheduleLayout;			//学生课表界面
	private ArrayList<StuCourseBean> mCourseList;	//课表数据
	//课表界面显示的参数
	private float cellWith		= 155;					//一堂课显示空间的宽度
	private float cellHeight	= 100;					//一堂课显示空间的高度
	private float titleHeight   = 50;					//时间标题的高度
	
	private LayoutInflater mInflater;
	
	private int nPlace;					//显示课表时使用的变量
	private int nRowNum = 7;			//课表的正文列数
	private int nCurrentEditPlace;		//当前正在编辑的课表位置

	private ArrayList<CoursePoint> coursePoints = new ArrayList<CoursePoint>();
	private DatabaseAdapter dbAdapter;
	private int nRole;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_short_course);
		
		initView();
		setListener();
		
		if (getDataFromFile()) {
			
		} else {
			Toast.makeText(ShortCourseActivity.this, "没有本地数据！",
					Toast.LENGTH_LONG).show();
		}
		createScheduleView();
	}

	private void initView(){
		mBtnBack				= (Button) findViewById(R.id.button_back);
		application				= (XhuApplication) getApplication();
		mResources 			    = getResources();
		mScheduleLayout			= (LinearLayout) findViewById(R.id.container);
		mRexh				= (Button) findViewById(R.id.button_xh);
		mInflater				= LayoutInflater.from(this);
		
		dbAdapter = new DatabaseAdapter(this);
		nRole = application.getRole();
	}
	
	
	public int getR(){
		return nRole;
	}
	/**
	 * 加载课表信息
	 * @param loadFromFile:是否加载本地文件中的课表信息，true-加载本地信息
	 */
	private void loadSchedule(boolean loadFromFile){
		/*mBtnBack.post(new Runnable() {
			public void run() {
				LoadingDialog.showWindow(ShortCourseActivity.this);
			}
		});*/
		
		/**
		 * 从文件中加载课表数据，如果没有则网络请求
		 */
		if (loadFromFile)
		if (getDataFromFile()){
			
			createScheduleView();
			
			/*mBtnBack.post(new Runnable() {
				public void run() {
					LoadData.clear();
			    	finish();
				}
			});*/
			
			return;
		}
		
		//对请求参数进行判断，检查是否是未登录模式的操作
		if (null == application.getScheduleUrl() || application.getScheduleUrl().equals("")
			|| null == application.getRefererUrl() || application.getRefererUrl().equals("")
			|| application.isLogin() == false){
			
			/*mBtnBack.post(new Runnable() {
				public void run() {
					LoadingDialog.dismiss();
					Toast.makeText(ShortCourseActivity.this, R.string.login_hint, Toast.LENGTH_LONG).show();
				}
			});*/
			
			return;
		}
		
		RequestParameter parameter = new RequestParameter();
		parameter.add("url", application.getScheduleUrl());
		parameter.add("referer", application.getRefererUrl());
		
		if (application.getRole() == XhuApplication.TEACHER){
			parameter.add("type", "教师");
			parameter.add("name", application.getUserName().replace("老师", ""));
			
		}else 
			parameter.add("name", application.getUserName().replaceAll("同学", ""));
		
		LoadData.loadData(Constant.SCHEDULE_DATA, parameter, new RequestListener() {
			public void onError(ClientError ed) {
				LoadingDialog.dismiss();
				ErrorShow.showError(ShortCourseActivity.this, ed);
			}
			public void onComplete(Object obj) {
				ScheduleData data = (ScheduleData) obj;
				
				mCourseList = data.getCourseList();
				
				if (null == mCourseList){
					LoadingDialog.dismiss();
					Toast.makeText(ShortCourseActivity.this, "没有课程信息", Toast.LENGTH_SHORT).show();
					return;
				}
				
				saveDataInFile();
				createScheduleView();
				
				LoadingDialog.dismiss();
				Toast.makeText(ShortCourseActivity.this, R.string.save_data_local_success, Toast.LENGTH_LONG).show();
			}
		});
	}
	
	/**
	 * 形成课表的界面
	 */
	private void createScheduleView(){
		//清除所有界面，在刷新课表的时候避免界面混乱
		mScheduleLayout.removeAllViews();
		mScheduleLayout.setPadding(dip2px(6), dip2px(6), dip2px(6), dip2px(6));
		//绘制表头
		LinearLayout layout = new LinearLayout(this);
		LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, dip2px(titleHeight));
		layout.setLayoutParams(params);
				
		//绘制课程表的表格
		mScheduleLayout.addView(getHorizontalSperator());
		for (int i=0; i<=7; i++){
			layout.addView(getVerticalView());
			
			LinearLayout titleView = new LinearLayout(this);
			LinearLayout.LayoutParams params2 = new LayoutParams(dip2px(cellWith), LayoutParams.FILL_PARENT);
			titleView.setLayoutParams(params2);
			titleView.setGravity(Gravity.CENTER);
			
			TextView title	= new TextView(this);
			title.setTextColor(Color.BLACK);
			setTextView(title, i);
			titleView.addView(title);
			
			layout.addView(titleView);
		}
		layout.addView(getVerticalView());
		mScheduleLayout.addView(layout);
		
		//分割符
		mScheduleLayout.addView(getHorizontalSperator());
		
		//绘制课表主体部分，5行7列
		for (int i=0; i<5; i++){
			layout = new LinearLayout(this);
			params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, dip2px(cellHeight));
			layout.setLayoutParams(params);
			layout.setOrientation(LinearLayout.HORIZONTAL);
			
			for (int j=0; j<8; j++){
				layout.addView(getVerticalView());
				
				RelativeLayout cellView = (RelativeLayout) mInflater.inflate(R.layout.course_cell, null);
				RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(dip2px(cellWith), dip2px(cellHeight));
				cellView.setLayoutParams(params2);
				
				TextView cTitle = (TextView) cellView.findViewById(R.id.textview_coursetitle);
				TextView cName = (TextView) cellView.findViewById(R.id.textview_coursename);
				TextView cPlace = (TextView) cellView.findViewById(R.id.textview_courseplace);
				TextView cTea	= (TextView) cellView.findViewById(R.id.textview_courseteacher);
				TextView cTime = (TextView) cellView.findViewById(R.id.textview_coursetime);
				TextView cRemark = (TextView) cellView.findViewById(R.id.textview_courseremark);
				TextView cMore = (TextView) cellView.findViewById(R.id.textview_more);
				
				//此处加载显示的文字内容
				if (j == 0){
					//显示时间
					cTitle.setVisibility(View.VISIBLE);
					cTitle.setText(getTime(i));
					
				}else {
					nPlace = transformCoord2Place(i, j-1, nRowNum);
					coursePoints.add(new CoursePoint(i, j-1));
					
					//显示课程表
					if (null == mCourseList){

					}else {
						//找到课程表
						String courseName="", place="", teacher="", time="", remark = "", more = "";
						
						Iterator<StuCourseBean> iterator = mCourseList.iterator();
						while (iterator.hasNext()){
							StuCourseBean bean = iterator.next();
							if (bean.x == i && bean.y == j-1){
								if (bean.name!=null && !bean.name.equals("null") && !bean.name.equals(""))
									courseName = bean.name;
								if (bean.site!=null && !bean.site.equals("null")&&!bean.site.equals(""))
									place = bean.site;
								if (bean.teacher!=null && !bean.teacher.equals("null")&&!bean.teacher.equals(""))
									teacher = bean.teacher;
								if (bean.time!=null && !bean.time.equals("null")&&!bean.time.equals(""))
									time = bean.time;
								if (bean.remark!=null && !bean.remark.equals("null") && !bean.remark.equals(""))
									remark = bean.remark;
								if (bean.more!=null && !bean.more.equals("null") && !bean.more.equals(""))
									more = bean.more;
								
								break;
							}
						}
						cName.setText(courseName);
						cPlace.setText(place);
						cTea.setText(teacher);
						cTime.setText(time);
						cMore.setText(more);
						cRemark.setText(remark);
					}
				}
				
				layout.addView(cellView);
			}
			layout.addView(getVerticalView());
			mScheduleLayout.addView(layout);
			mScheduleLayout.addView(getHorizontalSperator());
			if (i == 1 || i== 3){
				//上午和下午，下午和晚上之间需要加2条分隔线
				LinearLayout sperator = new LinearLayout(this);
				sperator.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, dip2px(2)));
				mScheduleLayout.addView(sperator);
				mScheduleLayout.addView(getHorizontalSperator());
			}
		}
	}
	
	
	
	
	/**
	 * 获取水平分割栏
	 * @return : 水平分隔符View对象
	 */
	private View getHorizontalSperator()
	{
		View horizontalView = new View(this);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT, 	dip2px(1f));
		
		horizontalView.setLayoutParams(params);
		horizontalView.setBackgroundResource(R.color.color_dark_grey);
		
		return horizontalView;
	}
	
	/**
	 * 获取垂直分割符
	 * @return ： 垂直分割符View对象
	 */
	private View getVerticalView()
	{
		View verticalView = new View(this);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dip2px(1f), 
				LinearLayout.LayoutParams.FILL_PARENT);
		
		verticalView.setLayoutParams(params);
		verticalView.setBackgroundResource(R.color.color_dark_grey);
		return verticalView;
	}
	
	private int dip2px(float dpValue) {
		final float scale = mResources.getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}
	
	/**
	 * 设置标题栏名字
	 * 
	 * @param textView
	 *            ： 标题栏对应的View
	 * @param i
	 *            ： 标题栏序号，对应为星期一，星期二。。。
	 */
	private void setTextView(final TextView textView, final int i) {
		switch (i) {
			case 0 :
				textView.setText("时间");
				break;
			case 1 :
				textView.setText("星期一");
				break;
			case 2 :
				textView.setText("星期二");
				break;
			case 3 :
				textView.setText("星期三");
				break;
			case 4 :
				textView.setText("星期四");
				break;
			case 5 :
				textView.setText("星期五");
				break;
			case 6 :
				textView.setText("星期六");
				break;
			case 7 :
				textView.setText("星期日");
				break;
		}
	}
	
	private String getTime(int i){
		switch (i) {
		case 0:
			return "第1,2节";
		case 1:
			return "第3,4节";
		case 2:
			return "第5,6节";
		case 3:
			return "第7,8节";
		case 4:
			return "晚上";
		}
		
		return "错误时间";
	}
	
	/**
	 * 从文件中获取课表以及备注信息
	 * @return:true-获取信息成功，false-获取信息失败
	 */
	private boolean getDataFromFile(){
		//查看是否有课表数据存在，没有则返回
		dbAdapter.openDatabase();
		int k = dbAdapter.hasDataInTimeTable(nRole);
		dbAdapter.closeDatabase();
		if (0 == k)
			return false;
		
		boolean flag = false;
		ArrayList<StuCourseBean> courseList = new ArrayList<StuCourseBean>();
		for (int i=0; i<=4; i++){
			for (int j=0; j<=6; j++){
				dbAdapter.openDatabase();
				StuCourseBean bean = dbAdapter.getOneTimeTable(nRole, i + "" + j);
				dbAdapter.closeDatabase();
				if (bean.name != null)
					flag = true;
				
				courseList.add(bean);
			}
		}
		
		mCourseList = courseList;
		courseList = null;
		
		return flag;
	}
	
	/**
	 * 将课表信息保存在文件中
	 */
	private void saveDataInFile(){
		if (null == mCourseList)
			return;
		
		Iterator<StuCourseBean> iterator = mCourseList.iterator();
		while (iterator.hasNext()) {
			StuCourseBean stuCourseBean = (StuCourseBean) iterator.next();
			saveData(stuCourseBean);
		}
	}
	
	private void saveData(StuCourseBean stuCourseBean){
		dbAdapter.openDatabase();
		dbAdapter.saveOneTimeTable(nRole, stuCourseBean);
		dbAdapter.closeDatabase();
	}
	
	/**
	 * 为控件添加点击事件
	 */
	private void setListener(){
		mBtnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				LoadData.clear();
		    	finish();
			}
		});
		
		mRexh.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(ShortCourseActivity.this, XihuaClientActivity.class);
				startActivity(intent);
			}
		});
	}
	
	/**
	 * 初始化列表
	 */
	private void initList(){
		mCourseList = new ArrayList<StuCourseBean>();
		for (int i=0; i<5; i++){
			for (int j=0; j<7; j++){
				StuCourseBean bean = new StuCourseBean();
				bean.x = i;
				bean.y = j;
				mCourseList.add(bean);
			}
		}
	}

	class ModifyCourseListener{
		private int place;		//要显示到界面的数据在ArrayList<StuCourseBean> mCourseList中的位置
		public ModifyCourseListener(int place){
			this.place = place;
		}
	}
	
	/**
	 * 将坐标转化为mCourseList中的位置
	 * @param x：0～4
	 * @param y：0～6
	 * @param n:一行的个数
	 * @return
	 */
	private int transformCoord2Place(int x, int y, int n){
		return (y + x*n);
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK){
			if (LoadingDialog.isShowing())
				LoadingDialog.dismiss();
			else {
				LoadData.clear();
		    	finish();
			}
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}
}
